package jp.dev7.android.http;

import jp.dev7.android.exception.ApplicationException;

import org.apache.http.client.params.ClientPNames;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.ClientConnectionManagerFactory;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.SingleClientConnManager;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

/**
 * HTTPS用のクライアント。サーバー証明をすべて信頼する。
 * 
 * @author narazaki.daishi
 */
public class NoneSSLVerifierHttpClient extends DefaultHttpClient {

    /** http port. */
    private static final int HTTP_PORT = 80;

    /** https port. */
    private static final int HTTPS_PORT = 443;

    /** TIME OUT. */
    private static final int TIMEOUT = 10000;

    @Override
    protected ClientConnectionManager createClientConnectionManager() {
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory
            .getSocketFactory(), HTTP_PORT));

        SSLSocketFactory sslSocketFactory = null;
        try {
            sslSocketFactory = NoneSSLVerifierSSLSocketFactory.create();
        } catch (Exception e) {
            throw new ApplicationException(e);
        }

        sslSocketFactory
            .setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        registry.register(new Scheme("https", sslSocketFactory, HTTPS_PORT));

        ClientConnectionManager connectionManager = null;
        HttpParams params = getParams();

        HttpConnectionParams.setConnectionTimeout(params, TIMEOUT);
        HttpConnectionParams.setSoTimeout(params, TIMEOUT);

        ClientConnectionManagerFactory connectionManagerFactory = null;

        String className =
            (String) params
                .getParameter(ClientPNames.CONNECTION_MANAGER_FACTORY_CLASS_NAME);
        if (className != null) {
            try {
                Class<?> clazz = Class.forName(className);
                connectionManagerFactory =
                    (ClientConnectionManagerFactory) clazz.newInstance();
            } catch (Exception e) {
                throw new ApplicationException(e);
            }
        }

        if (connectionManagerFactory != null) {
            connectionManager =
                connectionManagerFactory.newInstance(params, registry);
        } else {
            connectionManager =
                new SingleClientConnManager(getParams(), registry);
        }

        return connectionManager;
    }
}
